//
// Created by Administrator on 2023/12/14.
//

#include <jni.h>
#include <string>
#include <android/bitmap.h>
#include <malloc.h>
extern "C"{
#include "jpeglib.h"
}
void writeToPath(uint8_t *tmpdata, const char *cpath, int w, int h,int quality);

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_palette_activity_SevenActivity_generateString(JNIEnv *env, jobject thiz) {
        std::string hello = "Hello World";
    return env->NewStringUTF(hello.c_str());
}

void writeToPath(uint8_t *data, const char *path, int w, int h,int quality) {
    struct jpeg_compress_struct jpeg_struct;
    jpeg_error_mgr jpeg_error;
    jpeg_struct.err = jpeg_std_error(&jpeg_error);
    jpeg_create_compress(&jpeg_struct);
    FILE * file = fopen(path,"wb");
    jpeg_stdio_dest(&jpeg_struct,file);
    jpeg_struct.image_width = w;
    jpeg_struct.image_height = h;
    jpeg_struct.input_components = 3;
    jpeg_struct.in_color_space = JCS_EXT_RGB;
    jpeg_struct.arith_code = FALSE;
    jpeg_set_defaults(&jpeg_struct);
    jpeg_set_quality(&jpeg_struct,quality, TRUE);
    jpeg_start_compress(&jpeg_struct,TRUE);
    JSAMPROW row_pointer[1];
    while (jpeg_struct.next_scanline < h){
        row_pointer[0] = &data[jpeg_struct.next_scanline*w*3];
        jpeg_write_scanlines(&jpeg_struct,row_pointer,1);
    }
    jpeg_finish_compress(&jpeg_struct);
    fclose(file);
    jpeg_destroy_compress(&jpeg_struct);
}

extern "C" JNIEXPORT void JNICALL
Java_com_example_palette_util_Huffman_nativeCompressBitmap(JNIEnv *env, jclass clazz, jobject jbitmap,
                                               jstring jpath,jint quality) {
    const char * cpath = env->GetStringUTFChars(jpath,0);
    AndroidBitmapInfo bitmapInfo;
    AndroidBitmap_getInfo(env,jbitmap,&bitmapInfo);
    int h = bitmapInfo.height;
    int w = bitmapInfo.width;
    uint8_t * pixels;
    AndroidBitmap_lockPixels(env, jbitmap, reinterpret_cast<void **>(&pixels));
    uint8_t * data, * tmpdata;
    data = static_cast<uint8_t *>(malloc(w * h * 3));
    tmpdata = data;
    uint8_t r ,g ,b;
    int color;
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            color = *(int *)pixels;
            r = (color & 0x00FF0000) >> 16;
            g = (color & 0x0000FF00) >> 8;
            b = (color & 0x000000FF);
            *data = b;
            *(data+1) = g;
            *(data+2) = r;
            data += 3;
            pixels += 4;
        }
    }
    writeToPath(tmpdata,cpath,w,h,quality);
    AndroidBitmap_unlockPixels(env,jbitmap);
    env->ReleaseStringUTFChars(jpath,cpath);
}